package com.project.restaurant.common.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.restaurant.common.api.ResponseResult;
import com.project.restaurant.common.api.ServiceStateCode;
import com.project.restaurant.common.key.SessionAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 服务访问权限拦截，如果服务是需要登录后才可以访问的，则拦截该请求，不让去访问
 * @Description: 服务访问权限拦截器
 * @Author: 黄志鹏
 * @Date: 2022/10/13
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if(session.getAttribute(SessionAttribute.NOW_LOGIN_USER)==null){
            ResponseResult<Object> failResult = ResponseResult.auto(ServiceStateCode.LOGIN_AFTER_OPERATION, null);
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write(objectMapper.writeValueAsString(failResult));
            return false;
        }
        /*如果拦截成功false，则后面的方法全都不会调用
           如果为true，代表流向下一个拦截器的preHandle处理。如果是最后一个则流向处理器类映射的方法处理，
           处理完后开始往回走，拦截器链顺序从尾到头调用postHandler方法，直到视图返回。即视图已经呈现在客户端了
           返回后也是重新从拦截器链尾到头调用afterCompletion方法
        * */
        return true;
    }
}
